package com.njupt.webapp.tags;

import java.util.List;

import javax.servlet.jsp.JspException;

import org.springframework.jdbc.core.JdbcTemplate;

public class SqlQueryForlist extends SqlBaseTag{

	public Integer pageNo = 1;
	public Integer pageSize;
	public String dbType;
	public int doStartTag() throws JspException {
		String nativeSql = (String) TagUtils.evaluate("sql",sql, String.class,this,pageContext);
		if(pageSize != null){
			nativeSql = composePaginationSql(nativeSql,(pageSize*pageNo)-pageSize,pageSize);
		}
		JdbcTemplate template = super.getTemplate();
		try{
			List list = template.queryForList(nativeSql);
			TagUtils.saveToContext(this,pageContext,scope,list);
		}catch(Exception e){
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	public Integer getPageNo() {
		return pageNo;
	}
	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}
	public Integer getPageSize() {
		return pageSize;
	}
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
	private String composePaginationSql(String sql,int firstResult, int maxResults) {
		if("oracle".equals(dbType) || dbType == null)
		return "select * from ( select row_.*, rownum rownum_ from ( "+sql+") row_ ) where rownum_ <= "+(firstResult+maxResults)+" and rownum_ > "+firstResult;
		if("sqlserver".equals(dbType))throw new RuntimeException("尚未支持sqlserver");
		return sql;
	}
}
